package me.hekr.iotos.api.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import lombok.Data;
import me.hekr.iotos.api.IotClient;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import retrofit2.Call;

/** @author du */
@Data
public class Pagec<T> implements Serializable {

  private static final long serialVersionUID = 5926676981594352187L;
  /** T 总条数 */
  private long totalElements;

  /** 当前页码 */
  private int page;

  /** 分页大小 */
  private int size;
  /** 内容 */
  private List<T> content;

  public static <T> Pagec<T> transFrom(Page<T> page) {
    Pagec<T> pagec = new Pagec<>();
    pagec.setContent(page.getContent());
    pagec.setPage(page.getPageable().getPageNumber());
    pagec.setSize(page.getPageable().getPageSize());
    pagec.setTotalElements(page.getTotalElements());
    return pagec;
  }

  public static <T> Pagec<T> of(int page, int size) {
    Pagec<T> pagec = new Pagec<>();
    pagec.page = page;
    pagec.size = size;
    return pagec;
  }

  public static <T> List<T> getAll(int size, PageCall<T> request) {
    List<T> result = new ArrayList<>();
    for (int i = 0; ; i++) {
      Call<Pagec<T>> call = request.onPage(i, size);
      Pagec<T> page = IotClient.execute(call);
      result.addAll(page.content);
      if (page.content.size() < size) {
        break;
      }
    }
    return result;
  }

  /**
   * 总页数
   *
   * @return 总页数
   */
  public int getTotalPages() {
    return this.size == 0 ? 1 : (int) Math.ceil((double) totalElements / (double) this.size);
  }

  public List<T> getContent() {
    return content == null ? Collections.emptyList() : content;
  }

  public PageRequest toPageRequest() {
    return PageRequest.of(page, size);
  }

  public interface PageCall<T> {

    /**
     * 分页进行的时候，自定义处理
     *
     * @param page 当前页码，从0开始
     * @param size 分页大小
     * @return call
     */
    Call<Pagec<T>> onPage(int page, int size);
  }
}
